<template>
	<view class="checkReport">
		<u-toast ref="uToastc" />
		<view class="checkReportInfo">
			<view class="checkReportCard">
				<view class="checkReportCardInfo">
					<view class="title">{{checkQuestdata.name}}</view>
					<view class="titleMid"><text class="titleNag">{{checkQuestdata.industryName}}</text><text
							class="titleNag">{{checkQuestdata.institutionType}}</text>
					</view>
					<view class="adress">详细地址：{{checkQuestdata.name}}</view>
				</view>
			</view>
			<view class="checkReportItem">
				<view class="informationTitle">
					<view class="left">
						<image src="../../static/images/reportCheck.png" class="leftImg"></image>
						检查事项（必填）
					</view>
				</view>
				<view class="checkItem">
					<uni-forms :modelValue="checkQuestdata" :rules="dynamicRules" ref="checkRef">
						<view class="checkItemList" v-for="(it,index) in checkQuestdata.questionVOS" :key="index">
							<view class="checkItemTitle">{{it.questionLabel}}</view>
							<view class="checkItemCheck">
								<uni-forms-item label="" :name="`questionVOS[${index}].standardOrNot`" :rules="[
								                    {
								                      required: true,
								                      errorMessage: '请选择是否达标',
								                    }
								                  ]">
									<up-radio-group v-model="it.standardOrNot" placement="row" activeColor='#30B3FB'>
										<up-radio :customStyle="{marginRight: '140rpx'}"
											v-for="(item, index) in radiolist1" :key="index" :label="item.name"
											:name="item.standardOrNot" labelSize='28rpx' @change="radioChange(it,item)">
										</up-radio>
									</up-radio-group>
								</uni-forms-item>
							</view>
						</view>
						<view class="checkpload">
							<view class="checkploadTitle">现场照片</view>
							<up-upload :fileList="fileList1" @afterRead="afterRead" @delete="deletePic" name="1"
								multiple :maxCount="3" width="190rpx" height="160rpx"
								:previewFullImage="true"></up-upload>
						</view>
						<view class="checkpload">
							<view class="checkploadTitle">核查纪实</view>
							<up-textarea v-model="checkContent" placeholder="请输入内容" count maxlength='500'
								style="width: 93%;"></up-textarea>
						</view>
					</uni-forms>
				</view>

			</view>
		</view>
		<view class="botomBtn">
			<button class="btn" size="mini" @click="submit('checkRef')">提交</button>
			<button class="btn edit" size="mini" @click="closeCheckPage">取消</button>
		</view>
		<!-- 弹窗 -->
		<uni-popup ref="popup" background-color="#fff">
			<view class="popup-content">
				<view class="popupContentTitle">未达标</view>
				<!-- <view v-for="(item, index) in newObj.children" :key="index"> -->
				<view class="popupContentInfo ">
					<view class="checkpload">
						<view class="checkploadTitle">{{newObj.questionDetailLabel}}</view>
						<up-textarea v-model="verifyNoValue" placeholder="请输入内容" count maxlength='50'
							style="width: 95%;"></up-textarea>
					</view>
					<view class="checkpload" v-if="newObj.children">
						<view class="checkploadTitle">检查缺失项</view>
						<view class="popupContentInfoCheck">
							<up-checkbox-group v-model="newObj.lackItemList" placement="row" activeColor='#30B3FB'
								@change="checkboxChange">
								<up-checkbox v-for="(it, index) in newObj.children" :key="index"
									:label="it.questionDetailLabel" :name="it.questionDetailId" shape="circle"
									class="checkboxTsil">
								</up-checkbox>
							</up-checkbox-group>
						</view>
					</view>
				</view>
				<view class="botomBtnde">
					<button class="btn" size="mini" @click="detailDubmission(newObj.questionId)">提交</button>
					<button class="btn edit" size="mini" @click="closePopo(newObj.questionId)">取消</button>
				</view>
				<!-- </view> -->
			</view>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		onMounted,
		reactive,
		ref
	} from "vue";

	import {
		onLoad
	} from "@dcloudio/uni-app";
	import {
		uploadFiles
	} from '@/utils';
	import {
		institutionItem,
		taskAdd
	} from "@/api/unitsList.js"
	const checkContent = ref("")
	const verifyNoValue = ref("")
	const fileList1 = ref([]);
	// 消息提示引用
	const uToastc = ref(null)
	// 基本案列数据
	const radiolist1 = reactive([{
			name: '是,已达标',
			standardOrNot: 0
		},
		{
			name: '否，未达标',
			standardOrNot: 1
		},
	]);
	// 基本案列数据
	const checkboxList1 = reactive([]);

	const checkboxValue1 = ref(null);
	const standardOrNot = ref(null);
	const checkQuestdata = ref({})
	const checkRef = ref(null)
	const dynamicRules = ref({})
	// const checkEditRef = ref(null)
	onLoad((option) => {
		institutionInfolist(option.institutionId)
	})
	const institutionInfolist = async (institutionId) => {
		const res = await institutionItem(institutionId)
		console.log(1, res);
		checkQuestdata.value = res.data
	}
	// const questionDetailList = ref([])
	let questionDetailList = []
	const newObj = ref({})
	const popup = ref(null)
	const radioChange = (item, selectedRadio) => {
		// console.log(21, item.questionId);
		// console.log(22, selectedRadio.standardOrNot);
		if (selectedRadio.standardOrNot == 1) {
			const foundQuestion = checkQuestdata.value.questionVOS.find((it) => it.questionId === item.questionId);
			// 如果找到符合条件的对象，返回其 questionDetailList，否则返回空数组或者做其他处理
			questionDetailList = foundQuestion ? foundQuestion.questionDetailList : [];
			if (questionDetailList.length > 1) {
				// 将除了第一项以外的所有项合并到第一项的 children 属性中
				const firstObject = questionDetailList[0];
				firstObject.children = []; // 清空 children 数组
				for (let i = 1; i < questionDetailList.length; i++) {
					firstObject.children.push(questionDetailList[i]);
				}
				// 清空原数组中的其他项
				questionDetailList = [firstObject];
			}
			// 使用 Object.assign() 合并对象
			newObj.value = Object.assign({}, questionDetailList[0]);
			// console.log("过来11", questionDetailList);
			// ------------------------------
			popup.value.open('bottom')
		}
	};

	const fileVos = ref([])
	// 删除图片
	const deletePic = (event) => {
		fileList1.value.splice(event.index, 1);
	};
	// 新增图片
	const afterRead = async (event) => {
		// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
		let lists = [].concat(event.file);
		let fileListLen = fileList1.value.length;
		lists.map((item) => {
			fileList1.value.push({
				...item,
				status: 'uploading',
				message: '上传中',
			});
		});
		// console.log("所有图片", lists);
		// console.log("所有图片1", fileList1.value);
		for (let i = 0; i < lists.length; i++) {
			const result = await uploadFilePromise(lists[i].url);
			let item = fileList1.value[fileListLen];
			fileList1.value.splice(fileListLen, 1, {
				...item,
				status: 'success',
				message: '',
				url: result,
			});
			fileListLen++;
		}
	};
	const uploadFilePromise = (url) => {
		uploadFiles(url).then(res => {
			console.log("上传结果", res);
			if (res.code == 200) {
				fileVos.value.push({
					...res.data
				})
			}
		});
	}



	const checkboxChange = (n) => {
		checkboxValue1.value = n
		newObj.value.lackItemList = n
		// console.log('change弹窗11', checkboxValue1.value, newObj.value);
		// console.log('change弹窗212', n, newObj.value.lackItemList);
	};
	/**
	 * @Description:弹窗提交
	 * @returns
	 */
	const detailDubmission = async (questionId) => {
		// console.log(212222, newObj.value.lackItemList);
		// console.log("细节122", questionId, verifyNoValue.value, checkboxValue1.value);
		if (verifyNoValue.value == "") {
			uToastc.value.show({
				title: '请填写存在问题及其他情况',
				type: 'error',
				message: "请填写存在问题及其他情况",
				position: 'top'
			})
			return
		}
		if (newObj.value.children) {
			if (newObj.value.lackItemList == undefined) {
				uToastc.value.show({
					type: 'error',
					message: "请选择缺失项",
					position: 'top'
				})
				return
			}
		}
		checkQuestdata.value.questionVOS.forEach(id => {
			if (id.questionId === questionId) {
				id.description = verifyNoValue.value;
				// id.lackItemList = checkboxValue1.value
				id.lackItemList = newObj.value.lackItemList
			}
		})
		console.log("查看", checkQuestdata.value.questionVOS);
		// checkEditRef.value.validate().then(valid => {
		// 	if (valid) {
		// 		console.log("校验通过");
		popup.value.close('bottom')

		// 	} else {
		// 		console.log("校验失败");
		// 	}
		// })
	}
	/**
	 * @Description:弹窗关闭
	 * @returns
	 */
	const closePopo = async (id) => {
		verifyNoValue.value = ""
		checkQuestdata.value.questionVOS.forEach(item => {
			if (item.questionId === id) {
				item.standardOrNot = null
				item.description = null
				item.lackItemList = null
			}
		})
		popup.value.close()
	}
	const taskDetailReqVO = ref({})
	const closeCheckPage = async () => {
		uni.redirectTo({
			url: '/pages/index/index'
		});
	}
	const submit = async () => {
		taskDetailReqVO.value = {
			checkDate: checkQuestdata.value["checkDate"],
			checkContent: checkContent.value,
			institutionName: checkQuestdata.value["name"],
			policeStationId: checkQuestdata.value["policeStationId"],
			institutionId: checkQuestdata.value["institutionId"],
		}
		// console.log("打印提交1", checkQuestdata.value);
		// console.log("填写值的2", taskDetailReqVO.value);

		let obj = {
			answerItemList: checkQuestdata.value.questionVOS,
			fileVos: fileVos.value,
			taskDetailReqVO: taskDetailReqVO.value
		}

		checkRef.value.validate().then(valid => {
			if (valid) {
				// console.log("填写值的33", obj);
				// console.log("校验通过");
				taskAdd(obj).then(res => {
					if (res.code == 200) {
						uToastc.value.show({
							title: '提交成功',
							type: 'success',
							message: '提交成功',
							position: 'top'
						})
						checkQuestdata.value = {}
						uni.redirectTo({
							url: '/pages/index/index'
						});
					} else {
						uToastc.value.show({
							title: '提交失败',
							type: 'error',
							message: '提交失败',
							position: 'top'
						})
					}
				})
			} else {
				console.log("校验失败");
			}
		})
	}
</script>

<style lang="scss">
	.checkReport {
		width: 100%;
		height: 100vh;
		// height: calc(100vh - 88rpx);
		// background-color: pink;
		overflow-y: auto;
		background-color: #FAFAFA;
		;

		.checkReportCard {
			width: 92%;
			height: 20vh;
			margin: auto;
			margin-top: 20rpx;
			background-color: rgba(255, 255, 255, 0.9);
			box-shadow: 0px 0px 30px 0px rgba(70, 136, 211, 0.1);
			border-radius: 20rpx;
			display: flex;
			align-items: center;
			justify-content: center;

			.checkReportCardInfo {
				width: 92%;
				height: 88%;

				.title {
					font-family: PingFang SC;
					font-weight: bold;
					font-size: 32rpx;
					color: #333333;
					line-height: 60rpx;
				}

				.titleMid {
					width: 100%;

					.titleNag {
						font-family: PingFang SC;
						font-weight: 400;
						font-size: 28rpx;
						color: #0083FF;
						background: #BFD4E8;
						border-radius: 4rpx;
						padding: 4rpx 16rpx;
						margin-right: 10rpx;
						line-height: 60rpx;
					}

					.titleNag:last-child {
						background: #FFE8CE;
						color: #FF8700;
					}

				}

				.adress {
					font-family: PingFang SC;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
					// line-height: 100rpx;
				}
			}
		}

		.checkReportItem {
			width: 92%;
			height: 67vh;
			margin: auto;
			margin-top: 20rpx;
			background-color: rgba(255, 255, 255, 0.9);
			box-shadow: 0px 0px 30px 0px rgba(70, 136, 211, 0.1);
			border-radius: 20rpx;
			// display: flex;
			// align-items: center;
			// justify-content: center;

			.informationTitle {
				width: 94%;
				height: 80rpx;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin: auto;

				.left {
					width: 70%;
					height: 100%;
					display: flex;
					align-items: center;
					font-family: PingFang SC;
					font-weight: bold;
					font-size: 34rpx;
					color: #333333;
					line-height: 137rpx;

					.leftImg {
						width: 50rpx;
						height: 50rpx;
						margin-right: 15rpx;
					}
				}
			}

			.checkItem {
				width: 92%;
				height: calc(100% - 90rpx);
				margin: auto;
				// border: 1px solid red;
				overflow: auto;

				.checkItemList {
					width: 100%;

					.checkItemTitle {
						font-family: PingFang SC;
						font-weight: 500;
						font-size: 30rpx;
						color: #333333;
						line-height: 60rpx;
					}

					.checkItemCheck {
						// border: 1px solid blue;
					}
				}

				.checkpload {

					.checkploadTitle {
						font-family: PingFang SC;
						font-weight: 500;
						font-size: 30rpx;
						color: #333333;
						line-height: 60rpx;
					}
				}
			}
		}

		.botomBtn {
			width: 90%;
			height: 8%;
			display: flex;
			justify-content: center;
			align-items: center;
			position: fixed;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			// background-color: red;

			.btn {
				width: 60%;
				height: 80rpx;
				line-height: 80rpx;
				font-size: 30rpx;
				color: #ffffff;
				// background-color: #1373fd;
				border: unset;
				background: linear-gradient(-90deg, #00C2D3, #00A7FF);
				border-radius: 6rpx;
			}

			.edit {
				width: 30%;
				background: #ADADAD;
				border-radius: 6rpx;
			}
		}

		//弹窗样式
		.popup-content {
			width: 100%;
			height: 58vh;

			.popupContentTitle {
				font-family: PingFang SC;
				font-weight: bold;
				font-size: 34rpx;
				color: #333333;
				line-height: 80rpx;
				text-align: center;
			}

			.popupContentInfo {
				width: 90%;
				height: 42vh;
				margin: auto;

				.checkploadTitle {
					font-family: PingFang SC;
					font-weight: 500;
					font-size: 30rpx;
					color: #333333;
					line-height: 60rpx;
				}

				.popupContentInfoCheck {
					width: 96%;
					height: 16vh;
					margin: auto;
					overflow: auto;

					// border: 1px solid red;


					.checkboxTsil {
						width: 100%;
						margin-top: 20rpx;
					}
				}
			}

			.botomBtnde {
				width: 92%;
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 20rpx;
				margin: auto;

				.btn {
					width: 64%;
					height: 80rpx;
					line-height: 80rpx;
					font-size: 30rpx;
					color: #ffffff;
					// background-color: #1373fd;
					border: unset;
					background: linear-gradient(-90deg, #00C2D3, #00A7FF);
					border-radius: 6rpx;
				}

				.edit {
					width: 30%;
					background: #ADADAD;
					border-radius: 6rpx;
				}
			}
		}
	}
</style>